package BFS_DFS;

import java.util.Scanner;

//最小步数
public class DFS迷宫问题2 {
    static int n;
    static int m;
    static int[][] maze;
    static boolean[][] vis;
    static int[][] dir=new int[][]{
            {-1,0},{1,0},{0,-1},{0,1}
    };

    static int minStep=Integer.MAX_VALUE;//最小步数

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        maze=new int[n][m];
        vis=new boolean[n][m];
        int startX=-1,startY=-1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                maze[i][j]=sc.nextInt();
                if(maze[i][j] == 0 && startX == -1 && startY == -1){
                    startX = i;
                    startY = j;
                }
            }
        }
        sc.close();
        if(startX == -1 || startY == -1){
            System.out.println("no");
            return;
        }

        dfs(startX,startY,0);//初始步数为0
        if(minStep==Integer.MAX_VALUE){
            System.out.println("no");//没有找到路径
        }else{
            System.out.println(minStep);
        }
    }

    static void dfs(int x,int y,int steps){
        if(maze[x][y]==2){//找最小步数
            minStep= Math.min(minStep,steps);
            return;
        }
        vis[x][y]=true;
        for (int i = 0; i < 4; i++) {
            int tx=x+dir[i][0];
            int ty=y+dir[i][1];
            if(inMaze(tx,ty)&&!vis[tx][ty]&&(maze[tx][ty] == 0 || maze[tx][ty] == 2)){
                dfs(tx,ty,steps+1);
            }
        }
        vis[x][y]=false;//回溯，标记为未访问
    }

    static boolean inMaze(int x,int y){
        return (0<=x&&x<n&&0<=y&&y<m);
    }
}
